package com.elite.groovy.callback


import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.MessageDigest

/**
* @Title:是否黑名单验证API
* @Description:是否黑名单验证API
* @Param:
* @return:
* @Author: TH
* @Date: 2023/10/24
*/
public class apiIVRCheckBlackList implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiIVRCheckBlackList.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());


        // 初始化返回参数
        JSONObject result = new JSONObject();
        // 获取接口调用方式及参数
        String getMethod = httpServletRequest.getMethod();
        log.debug("[getMethod]:" + getMethod);




        StringBuilder sb = new StringBuilder();
        String sbString="";

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);


        //  入参为空
        if (KHUtil.isNull(inData)) {
            log.debug("【是否黑名单验证API接口】入参为空-无法完成操作!");
            result.put("status", -2);
            result.put("msg", "入参为空-无法完成操作!");
            result.put("data", "{}");
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiCheckBlackList", inData.toString(), result.toString(), "是否黑名单验证API接口");
            return result.toString();
        }








        try {
            //解析请求的jSON
            JSONObject inJson = JSONObject.fromObject(inData);
            String pretplcode = inJson.getString("pretplcode");
           // String InterfaceCode = inJson.getString("InterfaceCode");
            String segment = inJson.getString("segment");
            String posttplcode = inJson.getString("posttplcode");
            String phone = inJson.getString("phone");//手机号
            String tag = inJson.getString("tag");


            if (KHUtil.isNull(pretplcode)  || KHUtil.isNull(segment) || KHUtil.isNull(posttplcode) || KHUtil.isNull(phone)|| KHUtil.isNull(tag)) {
                log.debug("【是否黑名单验证API接口】参数值为空-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "参数值为空-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiCheckBlackList", inData.toString(), result.toString(), "是否黑名单验证API接口");
                return result.toString();
            }

            //判断是否是约定好的固定值
            if (!pretplcode.equals("Local_Interface_input")|| !segment.equals("formcond") || !posttplcode.equals("Interface_out_detail") || !tag.equals("tianrun")) {
                log.debug("【是否黑名单验证API接口】固定值不正确-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "固定值不正确-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiCheckBlackList", inData.toString(), result.toString(), "是否黑名单验证API接口");
                return result.toString();
            }








            //开始查找这条手机号在黑名单列表状态是在用的
            String selectsql = "select PHONENO   from SPECIALPHONE where PHONENO=? and STATUS='1' ";

            List<Map<String, Object>> selelctList = jt.queryForList(selectsql, phone);

            log.debug("selelctList数量：" + selelctList.size());
            //定义一个查询返回报文状态
            String isblack = null;
            if (selelctList.size() > 0) {
                log.debug("这条手机号是黑名单：" + phone);
                isblack = "Y";
            } else {
                log.debug("这条手机号不是黑名单：" + phone);
                isblack = "N";
            }

            result.put("InterfaceCode","sys_check_black");
            result.put("posttplcode","Interface_out_detail");
            result.put("pretplcode","Local_Interface_input");
            result.put("segment","formcond");
            result.put("phone",phone);
            result.put("uid","/extapi");
            result.put("company","davco");
            result.put("isblack",isblack);



            log.debug("【是否黑名单验证API接口】成功返回的JSON报文：" + result);
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiCheckBlackList", inData.toString(), result.toString(), "是否黑名单验证API接口");


        } catch (Exception e) {
            log.error("【是否黑名单验证API接口】数据处理错误:", e);
            result.put("status", -1);
            result.put("msg", "数据处理错误[" + e.getMessage() + "]");
            result.put("data", "{}");
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiCheckBlackList", inData.toString(), result.toString(), "是否黑名单验证API接口");
        }


        return result
    }
// MD5 加密 32 位
    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

}
